package practice2;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import util.HibernateUtil;

public class ItemDAO {

	public static void main(String[] args) throws InterruptedException {

		// ########## unit 1 ：插入 ##############
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		Item item = new Item("我的闲置物品", "物美价廉,童叟无欺", new Date(), new Date());
		Bid bid1 = new Bid(item);
		bid1.setSuccessful(false);
		Thread.sleep(100);
		Bid bid2 = new Bid(item);
		bid2.setSuccessful(true);

		item.addBid(bid1);
		item.addBid(bid2);

		System.out.println(" >>> item：执行持久化  <<<");
		session.save(item);

		System.out.println("\n");
		tx.commit();
		session.close();

		// ################### unit 2：查询 #############
		Session secondSession = HibernateUtil.getSessionFactory().openSession();
		System.out.println(" >>> 执行查询  <<<");
		Query q = secondSession.createQuery("from Item");
		List items = q.list();
		for (Iterator iter = items.iterator(); iter.hasNext();) {
			Item it = (Item) iter.next();
			System.out.println("订单名称：" + it.getName() + ",描述：" + it.getDescription());
			System.out.println("出价信息：");
			Set l = it.getBids();
			for (Iterator iterator = l.iterator(); iterator.hasNext();) {
				Bid b = (Bid) iterator.next();
				System.out.println("出价时间：" + b.getCreated() + ",出价状态：" + b.isSuccessful());
			}
			System.out.println();
			// System.out.println(loadedMsg.getCount());
		}

		System.out.println("\n");
		secondSession.close();

		// ########## unit 3 ：修改 ##############
		Session session3 = HibernateUtil.getSessionFactory().openSession();
		Transaction tx3 = session3.beginTransaction();
		Item i3 = (Item) items.get(0);
		i3.setDescription("谁用谁知道！");
		System.out.println(" >>> item：修改  <<<");
		session3.save(i3);
		System.out.println("\n");
		tx3.commit();
		session3.close();
	}
}
